//
//  HNStrengtheningClassApplicationCountListVC.m
//  优学荟管理系统
//
//  Created by edz on 2017/11/27.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNStrengtheningClassApplicationCountListVC.h"
#import "HNStrengtheningClassApplicationCountListModel.h"
#import "HNStrengtheningClassApplicationCountListCell.h"
#import "TeacherCourseSelectModel.h"
#import "TeacherCourseSelectView.h"
#import "ZYAddStrongCouseController.h"
#import "LLNavigationMidSearchItem.h"
#import "HMSignUpStrongCourseVC.h"

@interface HNStrengtheningClassApplicationCountListVC ()<UITableViewDelegate, UITableViewDataSource, HNStrengtheningClassApplicationCountListCellDelegate, UITextFieldDelegate>
/** 表单 */
@property (weak, nonatomic) IBOutlet UITableView *TableView;
/** 数据存放地 */
@property (nonatomic, strong) NSMutableArray *DataArr;
/** 当前的页 */
@property (nonatomic, assign) NSInteger CurrentPage;
/** 临时保存的页数 */
@property (nonatomic, assign) NSInteger TempPage;
/** 搜索的字符串 */
@property (nonatomic, copy) NSString *SearchStr;

@end

@implementation HNStrengtheningClassApplicationCountListVC

#pragma mark - 生命周期
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"申请表总列表";
    
    self.navigationItem.titleView = [self SearchView];
    
    // 配置TableView
    [self ConfigTableView];
}

#pragma mark - Config
/** 配置TableView */
- (void)ConfigTableView {
    // 设置代理
    self.TableView.delegate = self;
    self.TableView.dataSource = self;
    // 设置占位View
    self.TableView.tableFooterView = [UIView new];
    self.TableView.tableHeaderView = [UIView new];
    // 设置自动Cell高
    self.TableView.rowHeight = UITableViewAutomaticDimension;
    self.TableView.estimatedRowHeight = 200;
    // 增加刷新头
    self.TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 每次下拉刷新时都保存好当前的页数，预防刷新失败后页数错乱
        self.TempPage = self.CurrentPage;
        // 当前的刷新设为1
        self.CurrentPage = 1;
        // 获取数据
        [self RefreshData];
    }];
    // 增加刷新尾
    self.TableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 获取数据
        [self RefreshData];
    }];
    // 开始刷新
    [self.TableView.mj_header beginRefreshing];
}

/** 刷新失败时的页数处理 */
- (void)MgrPage {
    
    self.CurrentPage = self.TempPage;
}

/** 刷新状态 1结束刷新 2没有更多数据了 3刷新表单*/
- (void)MgrRefresh:(NSInteger)State {
    
    if (State == 1) {
        [self.TableView.mj_header endRefreshing];
        [self.TableView.mj_footer endRefreshing];
    } else if (State == 2) {
        [self.TableView.mj_footer endRefreshingWithNoMoreData];
    } else if (State == 3) {
        [self.TableView reloadData];
    } else  {
        // 无
    }
}

#pragma mark - 网络
- (void)RefreshData {
    
    NSDictionary *Params = @{
                             @"action":@"selTrainlesson",
                             @"pageNumber":@(self.CurrentPage),
                             @"lessonName":self.SearchStr
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id responseObj) {
        
        // 结束刷新
        [self MgrRefresh:1];
        // 数据处理
        if ([responseObj[@"code"] isEqualToNumber:@1000]) {
            // 拿到数据
            NSArray *Arr = responseObj[@"t"][@"dataList"];
            // 如果当前的页码是1就先清空原数据
            self.CurrentPage == 1 ? [self.DataArr removeAllObjects]:nil;
            // 如果没有数据就提示没数据了
            if (Arr.count == 0) {
                
                [self MgrRefresh:2];
            } else {
                // 终于有数据啦
                [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    // 处理模型转对象
                    [self.DataArr addObject:[[HNStrengtheningClassApplicationCountListModel alloc] init_ValuForKeyWithDict:obj]];
                }];
                self.CurrentPage += 1;
                [self MgrRefresh:3];
            }
        } else {
            // 数据获取失败
            [SVProgressHUD showErrorWithStatus:responseObj[@"msg"]];
            [self MgrPage];
        }
    } Fail:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:NetErr];
        [self MgrRefresh:1];
        [self MgrPage];
    }];
}


/** 获取老师 */
- (void)RefreshDataWithTeacher:(void (^)(NSArray <TeacherCourseSelectModel *>*Arr))Complete {
    
    [MBProgressHUD showHUD];
    NSDictionary *Params = @{
                             @"action":@"getTeacherByOid",
                             @"oid":[AccountTool shareAccountTool].currentAccount.oid
                             };
    [NetManager Get:LLBaseURL(@"lesson.do") Auth:YES Params:Params Success:^(id Obj) {
        
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            
            NSMutableArray *MutableArr = [NSMutableArray array];
            [Obj[@"t"] enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [MutableArr addObject:[TeacherCourseSelectModel HNObjectValuesForKey:obj]];
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                Complete ? Complete ([MutableArr copy]) : nil ;
            });
            
            
        } else {
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [MBProgressHUD showError:NetErr];
    }];
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HNStrengtheningClassApplicationCountListModel *Model = self.DataArr[indexPath.row];
    HNStrengtheningClassApplicationCountListCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell1"];
    if (Cell == nil) {
    
        Cell = [[NSBundle mainBundle] loadNibNamed:[HNStrengtheningClassApplicationCountListCell description] owner:nil options:nil][0];
    }
    Cell.Model = Model;
    Cell.Delegate = self;
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
}

#pragma mark - HNStrengtheningClassApplicationCountListCellD代理
/** 开设加强课 */
- (void)HNStrengtheningClassApplicationCountListCell:(HNStrengtheningClassApplicationCountListCell *)Cell ActionWithOpenStrengtheningClass:(UIButton *)Button andModel:(HNStrengtheningClassApplicationCountListModel *)Model {
    
    // 先获取老师的信息
    [self RefreshDataWithTeacher:^(NSArray<TeacherCourseSelectModel *> *Arr) {
        
        NSMutableArray *TitleArr = [NSMutableArray array];
        [Arr enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [TitleArr addObject:obj.petName];
        }];
        // 弹窗并选择老师
        TeacherCourseSelectView *View = [TeacherCourseSelectView ConfigWithArr:[TitleArr copy] Complete:^(NSInteger Index) {
            
            ZYAddStrongCouseController *VC = [[ZYAddStrongCouseController alloc] init];
            // 声明我这是增加课程
            
            VC.tearchIds = [[Arr[Index] uid] stringValue];
            
            VC.dataSelectSource = Model.elementCounts;
            VC.lessionId = [Model.ID stringValue];
//            VC.titleName = @"添加加强课程";
            VC.popBlock = ^{
                
                [self.DataArr removeAllObjects];
                self.TempPage = self.CurrentPage = 1;
                [self.TableView reloadData];
                [self.TableView.mj_header beginRefreshing];
            };
            
            
            [self.navigationController pushViewController:VC animated:YES];
        }];
        View.Title.text = @"请选择课程老师";
    }];

}

/** 加强课列表 */                              
- (void)HNStrengtheningClassApplicationCountListCell:(HNStrengtheningClassApplicationCountListCell *)Cell ActionWithStrengtheningClassList:(UIButton *)Button andModel:(HNStrengtheningClassApplicationCountListModel *)Model {
    //model.id;
    HMSignUpStrongCourseVC *vc = [HMSignUpStrongCourseVC new];
    vc.titleName = Model.name;
    vc.courseID =  [NSString stringWithFormat:@"%@",Model.ID];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - textfiled代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    self.SearchStr = textField.text;
    [self.DataArr removeAllObjects];
    self.TempPage = self.CurrentPage = 1;
    [self.TableView reloadData];
    [self.TableView.mj_header beginRefreshing];
    return YES;
}

#pragma mark - 自定义方法
- (UIView *)SearchView {
    
    LLNavigationMidSearchItem *midItem = [LLNavigationMidSearchItem new];
    midItem.frame = CGRectMake(0, 0, kScreenWidth - 120, 30);
    midItem.searchField.placeholder = @"搜索课程";
    midItem.searchField.delegate = self;
    midItem.searchField.returnKeyType =  UIReturnKeySearch;
    return midItem;
}
#pragma mark - 点击事件


#pragma mark - Get
- (NSMutableArray *)DataArr {
    if (!_DataArr) {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

- (NSString *)SearchStr {
    
    if (!_SearchStr) {
        
        _SearchStr = @"";
    }
    return _SearchStr;
}
@end

